package com.devdan.headsetfix;



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.Log;



public class HeadsetfixHandle extends BroadcastReceiver {
	
	public boolean buttonAction = true; //true: redial, false: voice dialer
	@Override
	public void onReceive(Context context, Intent intent) {
    	String tag = null;		

	    if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
	    	Log.d(tag,"Button was pressed");
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
    	    	// Abort broadcast, otherwise media player will start playing.
    			abortBroadcast();   	    	
    	    	if (buttonAction) {
    	    		redial(context); 
    	    	}
    	    	else {
    	    		showVoiceDialer(context);
    	    	}
            }	    	
	    }	
	}
	
	private void redial(Context context) {
		String number = android.provider.CallLog.Calls.getLastOutgoingCall(context);
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +  number));
        callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(callIntent);
	}
	
	private void showVoiceDialer(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClassName("com.android.voicedialer", "com.android.voicedialer.VoiceDialerActivity");
        context.startActivity(intent);
		
	}

	public void setButtonAction(boolean b) {
		buttonAction = b;
	}
	
}